using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Data.Objects;
using System.Diagnostics;
using Common.Unity.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NorthwindEFModel;
using Testing.Core;

namespace Common.Unity.Extensions.Entity.Testing
{
	[TestClass]
	[DeploymentItem( "Common.Unity.Extensions.Entity.Testing/Resources/NorthwindEF.mdf" )]
	[DeploymentItem( "Common.Unity.Extensions.Entity.Testing/Resources/NorthwindEFModel.csdl" )]
	[DeploymentItem( "Common.Unity.Extensions.Entity.Testing/Resources/NorthwindEFModel.msl" )]
	[DeploymentItem( "Common.Unity.Extensions.Entity.Testing/Resources/NorthwindEFModel.ssdl" )]
	public class EntityQueryRetrievalPolicyTests : UnityContainerTestBase
	{
		[TestMethod, Owner( TestOwners.MichaelD_Bang )]
		public void VerifyExistingEntityIsRetrievedCorrectly()
		{
			var item = Container.Resolve<Product>( new { ID = 36 } );
			Assert.IsNotNull( item );
			Assert.IsFalse( item.CategoryReference.IsLoaded );
			Assert.AreEqual( 36, item.ProductID );
			Assert.AreEqual( EntityState.Unchanged, item.EntityState );
		}

		[TestMethod, Owner( TestOwners.MichaelD_Bang )]
		public void VerifyExistingEntityWithRelationshipPropertyIsRetrievedCorrectly()
		{
			var item = Container.Resolve<Product>( "LoadWithCategory", new { ID = 36 } );
			Assert.IsNotNull( item );
			Assert.IsTrue( item.CategoryReference.IsLoaded );
			Assert.IsNotNull( item.Category );
			Assert.AreEqual( 8, item.Category.CategoryID );
			Assert.AreEqual( EntityState.Unchanged, item.EntityState );
		}

		[TestMethod, Owner( TestOwners.MichaelD_Bang )]
		public void VerifyExistingEntityWithDeepRelationshipPropertyIsRetrievedCorrectly()
		{
			var item = Container.Resolve<Customer>( new { ID = "DUMON" } );
			Assert.IsNotNull( item );
			Assert.IsTrue( item.Orders.IsLoaded );
			Assert.AreEqual( 4, item.Orders.Count );
			var orderDetails = item.Orders.First().OrderDetails;
			Assert.IsTrue( orderDetails.IsLoaded );
			Assert.AreEqual( 2, orderDetails.Count );

			var reference = orderDetails.First().ProductReference;
			Assert.IsFalse( reference.IsLoaded );
			Assert.IsNull( orderDetails.First().Product );
		}

		[TestMethod, Owner( TestOwners.MichaelD_Bang )]
		public void VerifyEnumerableOfEntityIsRetrievedCorrectly()
		{
			var category = "Confections";
			var items = Container.Resolve<IEnumerable<Product>>( "ProductsByCategory", new { Category = category } );
			Assert.AreEqual( 13, items.Count() );

			foreach ( var item in items.ToList() )
			{
				if ( !item.CategoryReference.IsLoaded )
				{
					item.CategoryReference.Load();
				}
				Assert.AreEqual( category, item.Category.CategoryName );
				Assert.AreEqual( EntityState.Unchanged, item.EntityState );
			}
		}
	}
}